using AutoMapper;
using B.S.BasicData.Api.Write.Application.Command.Customer;
using B.S.BasicData.Domain.Entities;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interfaces;
using MediatR;
using System.Transactions;
using Yitter.IdGenerator;

namespace B.S.BasicData.Api.Write.Application.CommandHandler.Customer
{
    public class CreateCustomerHandler : IRequestHandler<CreateCustomerCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<CustomerModel> customerRepo;
        private readonly ILogger<CreateCustomerHandler> logger;

        public CreateCustomerHandler(
            IBaseRepository<CustomerModel> customerRepo,
            ILogger<CreateCustomerHandler> logger)
        {
            this.customerRepo = customerRepo;
            this.logger = logger;
        }

        public async Task<ApiResult<int>> Handle(CreateCustomerCommand request, CancellationToken cancellationToken)
        {
            using (TransactionScope tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    // 验证请求
                    if (string.IsNullOrEmpty(request.Name))
                    {
                        return new ApiResult<int> { Code = ApiEnums.Error, Msg = "客户名称不能为空" };
                    }

                    // 检查手机号是否已存在
                    if (!string.IsNullOrEmpty(request.Phone))
                    {
                        var existingCustomer = (await customerRepo.Query())
                            .FirstOrDefault(x => x.Phone == request.Phone && !x.IsDeleted);
                        if (existingCustomer != null)
                        {
                            return new ApiResult<int> { Code = ApiEnums.Error, Msg = "该手机号已被注册" };
                        }
                    }

                    // 创建客户实体
                    var customer = new CustomerModel
                    {
                        Id = YitIdHelper.NextId(),
                        Name = request.Name,
                        Email = request.Email,
                        Phone = request.Phone,
                        Address = request.Address,
                        IsDeleted = false
                    };

                   
                    
                    tran.Complete();
                    logger.LogInformation($"新增客户成功：{customer.Id}");

                    return new ApiResult<int>
                    {
                        Code = ApiEnums.Success,
                        Msg = "新增客户成功",
                        Data = (int)customer.Id
                    };
                }
                catch (Exception ex)
                {
                    logger.LogError($"新增客户失败：{ex.Message}");
                    throw;
                }
            }
        }
    }
}